package com.gametime.setup;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Random;

import com.gametime.model.Player;
import com.gametime.model.Position;
import com.gametime.util.DBUtils;

public class ExperienceGenerator {

	private static ExperienceGenerator instance =null;
	private int maxRows=0;
	private ExperienceGenerator() throws Exception
	{
		Connection conn=null;
		try{
			conn = DBUtils.getInstance().getConnection();
			int result=0;
			final String sql="select count(*) from gen_exp";
			PreparedStatement ps =  conn.prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			while (rs.next())
			{
				maxRows= rs.getInt(1); 
			}
			rs.close();
			ps.clearParameters();
			ps.close();
		}catch(Exception e)
		{
			e.printStackTrace();
			throw e;
			
		}finally
		{
			DBUtils.closeConnection(conn);
		}
	}
	
	public static ExperienceGenerator getInstance() throws Exception
	{
		if(instance == null)
			instance = new ExperienceGenerator();
		return instance;
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	
	public int getExperience(Player p) throws Exception
	{
		Connection conn=null;
		int value =-1;
		try{
			conn = DBUtils.getInstance().getConnection();
			Random r = new Random();
			int randRow = r.nextInt(maxRows) + 1;
			value = getValue(randRow, conn);
			value  = adjustValue(value, p, conn);
			
		}catch(Exception e)
		{	
			e.printStackTrace();
			throw e;
		}finally
		{
			DBUtils.closeConnection(conn);
		}
		return value;
	}

	private int adjustValue(int value, Player p, Connection conn) {
		Position pos = p.getPosition();
		if(pos.getPositionId() < 3 && value > 10)
			value = value - 2;
		else if (pos.getPositionId() < 6 && value > 10)
			value = value - 1;
		
		return value;
	}

	private int getValue(int randRow, Connection conn) throws Exception {
		int result=0;
		final String sql="select value from gen_exp where gen_exp_weight_id =?";
		PreparedStatement ps =  conn.prepareStatement(sql);
		ps.setInt(1, randRow);
		ResultSet rs = ps.executeQuery();
		while (rs.next())
		{
			result= rs.getInt(1); 
		}
		rs.close();
		ps.clearParameters();
		ps.close();
		return result;
	}

	private int getMaxRows() {
		// TODO Auto-generated method stub
		return 0;
	}

}
